<template>
  <div>
    <div class="fixed w-300px h-600px bg-[var(--el-bg-color)] top-120px z-10 overflow-y-auto">
      <editorSet :initParams="baseParams" :groupApi="getGroups" @submit="submit"></editorSet>
    </div>
    <WangEditor :baseInfo="initParams" ref="editorRef" :has-author="false" :is-show-card="false"></WangEditor>
  </div>
</template>

<script setup lang="ts">
import WangEditor from "@/components/WangEditor/index.vue";
import { getGroups, createActive, getActive, editActive } from "@/api/modules/active";
import editorSet from "../components/editSet.vue";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { onBeforeMount } from "vue";

const initParams = reactive({ cont: "", title: "" });
const baseParams = reactive({ cover: "", group: 0 });

const router = useRouter();
const route = useRoute();

const editorRef = ref<InstanceType<typeof WangEditor> | null>();

const submit = async (params: any) => {
  if (!params || !editorRef.value?.getEditor()) return;
  try {
    if (/<img\b[^>]*>/gi.test(editorRef.value.getEditor()!.cont)) {
      params.hasImg = true;
    }
    if (/<video\b[^>]*>/gi.test(editorRef.value.getEditor()!.cont)) {
      params.hasVideo = true;
    }
    params.louPanId = parseInt(route.query.louPanId as string);
    if (!route.query.id) {
      await createActive({ ...params, ...editorRef.value?.getEditor() });
    } else {
      await editActive({ id: parseInt(route.query.id as string), ...params, ...editorRef.value?.getEditor() });
    }

    ElMessage.success("成功");
    router.back();
  } catch (error) {}
};

onBeforeMount(async () => {
  if (route.query.id) {
    const { data } = (await getActive(parseInt(route.query.id as string))) as any;
    initParams.cont = data.cont.content;
    initParams.title = data.title;
    baseParams.cover = data.cover;
    baseParams.group = data.group;
  }
});
</script>

<style></style>
